<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>域名级别查询-结果页</title>
    <link href="/static/layui/css/layui.css" rel="stylesheet">
    <script src="/static/layui/layui.js"></script>
    <script src="/static/js/axios.min.js"></script>
    <script src="/static/js/FileSaver.min.js"></script>
    <script src="/static/js/xlsx.full.min.js"></script>
    <link rel="shortcut icon" href="/static/domain.ico"/>
</head>
<body>
<div class="layui-layout layui-layout-admin">
    <div class="layui-side layui-bg-black">
        <div class="layui-side-scroll">
            <ul class="layui-nav layui-nav-tree layui-nav-side">
                <li class="layui-nav-item layui-this"><a href="<?php echo $back_url;?>">域名级别查询</a></li>
            </ul>
        </div>
    </div>

    <div class="layui-body" style="top:15px;">
        <div style="padding-left: 16px;padding-right: 16px;">
            <form class="layui-form" action="">
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">处理结果</label>
                    <div class="layui-input-block">
                        <table class="layui-table">
                            <colgroup><col width="80"><col width="300"><col width="120"><col width=""></colgroup>
                            <thead><tr><th>序号</th><th>域名</th><th>后缀</th><th id="copy-btn">说明-点击复制</th></tr></thead>
                            <tbody>
                            <?php if(!empty($domains)){foreach ($domains as $item){?>
                                <tr>
                                    <td><?php echo $item['index'];?></td>
                                    <td id="domain-<?php echo $item['index'];?>"><?php echo $item['domain'];?></td>
                                    <td id="ret-<?php echo $item['index'];?>"><?php echo $item['ret'];?></td>
                                    <td id="btn-<?php echo $item['index'];?>"><?php echo $item['body'];?></td>
                                </tr>
                            <?php }} ?>
                            </tbody>
                        </table>
                        <p>🔔🔔总计🔔🔔  共<?php echo $domain_count;?>笔</p>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <a href="<?php echo $back_url;?>" class="layui-btn"><i class="layui-icon layui-icon-backspace"></i>返回上一页 <<</a>
                        <a class="layui-btn layui-btn-primary layui-border" href="javascript:void(0)" id="exportExcelBtn"><i class="layui-icon layui-icon-down"></i>导出到Excel</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
    let socket;
    let url = "<?php echo $websocket_url;?>"; // WebSocket 服务器地址
    let reconnectInterval = 2000; // 重连间隔时间（毫秒）
    function connect() {
        socket = new WebSocket(url);

        socket.onopen = function (event) {
            console.log("WebSocket 连接已建立");
        };

        socket.onmessage = function (event) {
            console.log("收到消息:", event.data);
        };

        socket.onerror = function (error) {
            console.log("WebSocket 出错:", error);
        };

        socket.onclose = function (event) {
            console.log("WebSocket 连接关闭:", event);
            // 尝试重新连接
            setTimeout(connect, reconnectInterval);
        };
    }

    // 第一次连接，并在断开后2秒后可以重连
    connect();

    function sendMessage(message) {
        return new Promise((resolve, reject) => {
            socket.send(JSON.stringify(message));
            // 设置一个监听器以等待响应
            const listener = function (event) {
                const response = JSON.parse(event.data);
                if (response.domain === message.domain) {
                    socket.removeEventListener('message', listener);  // 清理监听器
                    resolve(response);  // 解析成功
                }
            };
            socket.addEventListener('message', listener);
        });
    }

    setInterval(() => {
        const tds = document.querySelectorAll('td');
        // 遍历所有 td 并筛选符合条件的元素
        tds.forEach(td => {
            const id = td.id; // 获取 id 属性
            const content = td.textContent;

            // 检查 id 是否存在并且以 'btn-' 开头
            if (id && id.startsWith('btn-') && content == '') {
                const index = id.match(/\d+/); // 匹配数字
                const domainTd = document.getElementById("domain-" + index);
                const domain = domainTd.textContent;

                sendMessage({flag: 'domain_level', domain: domain, index: index})
                    .then(response => {
                        // console.log("处理结果:", response);
                        const retTd = document.getElementById("ret-" + index);
                        retTd.textContent = response.ret;
                        td.textContent =response.body;
                    }).catch((err)=>{console.log('异常了',err)});
            }
        });
    }, 3000); // 每3秒更新

    // 导出到Excel
    document.getElementById('exportExcelBtn').addEventListener('click', function(e) {
        e.preventDefault(); // 阻止默认跳转

        // 1. 获取表格数据
        const table = document.querySelector('.layui-table')
        const workbook = XLSX.utils.table_to_book(table);

        // 2. 生成Excel文件并下载
        const now = new Date();
        const timestampSeconds = Math.floor(now.getTime() / 1000); // 秒级时间戳
        XLSX.writeFile(workbook, '域名级别-'+timestampSeconds+'.xlsx');
    });

    layui.use(['jquery', 'layer'], function(){
        var $ = layui.jquery;
        var layer = layui.layer;

        // 复制说明列
        $(document).on('click', '#copy-btn', function(){
            var columnIndex = 2; // 要复制的列索引
            var content = [];

            $('.layui-table tbody tr').each(function(){
                var text = $(this).find('td').eq(columnIndex).text().trim();
                if (text) {
                    content.push(text);
                }else{
                    content.push('');
                }
            });

            if (content.length === 0) {
                layer.msg('没有可复制的内容！', {icon: 2});
                return;
            }

            var textToCopy = content.join('\n');

            // 使用现代剪贴板API（推荐）
            if (navigator.clipboard) {
                navigator.clipboard.writeText(textToCopy)
                    .then(() => {
                        layer.msg('复制成功！', {icon: 1});
                    })
                    .catch(err => {
                        layer.msg('复制失败：' + err.message, {icon: 2});
                    });
            } else {
                // 降级方案（旧浏览器）
                var $temp = $('<textarea>');
                $('body').append($temp);
                $temp.val(textToCopy).select();
                document.execCommand('copy');
                $temp.remove();
                layer.msg('复制成功！', {icon: 1});
            }
        });
    });
</script>
</body>
</html>